const path = require('path')
const fs = require('fs')

//  \s 表示空白字符   \S表示
const regStyle = /<style>[\s\S]*<\/style>/

const regScript = /<script>[\s\S]*<\/script>/

fs.readFile(
  path.join(__dirname, './index.html'),
  'utf8',
  function (err, dataStr) {
    if (err) return console.log('读取HTML文件失败！' + err.message)
    resolveCss(dataStr)
    resolveJs(dataStr)
    resolveHtml(dataStr)
  }
)

function resolveCss(htmlStr) {
  const r1 = regStyle.exec(htmlStr)
  const newCss = r1[0].replace('<style>', '').replace('</style>', '')
  fs.writeFile(
    path.join(__dirname, './dist/index.css'),
    newCss,
    function (err) {
      if (err) return console.log('写入css失败', err.message)
      console.log('成功')
    }
  )
}

function resolveJs(htmlStr) {
  const r2 = regScript.exec(htmlStr)
  const newScript = r2[0].replace('<script>', '').replace('</script>', '')

  //   记得是三个参数，一个是文件路径，内容，和回调函数
  fs.writeFile(
    path.join(__dirname, './dist/index.js'),
    newScript,
    function (err) {
      if (err) return console.log('写入js失败', err.message)
      console.log('写入js成功')
    }
  )
}

function resolveHtml(htmlStr) {
  const newHtml = htmlStr
    .replace(regStyle, '<link rel="stylesheet" href="./index.css" />')
    .replace(regScript, '<script src="./index.js"></script>')
  fs.writeFile(
    path.join(__dirname, './dist/index.html'),
    newHtml,
    function (err) {
      if (err) return console.log('修改失败', err.message)
      console.log('修改html成功')
    }
  )
}
